<template>
  <div>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="意见建议" prop="remark">
        <div style="display: flex; flex-direction: column">
          <el-input
            v-model="form.remark"
            type="textarea"
            :maxlength="100"
            :show-word-limit="true"
            :input-style="{ height: '100px', width: '300px' }"
          />
        </div>
      </el-form-item>
      <el-form-item label="反馈截图" prop="auditImage">
        <el-upload
          class="upload-demo"
          ref="uploadRef"
          :limit="1"
          accept=".jpg,.png"
          :headers="upload.headers"
          :http-request="customUploadRequest"
          :show-file-list="false"
        >
          <!-- 如果有图片则显示上传的图片，否则显示上传图标 -->
          <div v-if="form.auditImage" class="avatar-wrapper">
            <img :src="form.auditImage" class="avatar" alt="图片" />
            <!-- 替换按钮（可选） -->
            <div class="replace-btn" @click.stop="handleRemove">替换图片</div>
          </div>
          <div v-else class="avatar-uploader">
            <el-icon class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" class="primary" @click="submitForm(formRef)"
          >提交</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="tsx" setup>
import { onMounted, reactive, ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, UploadInstance } from 'element-plus'; // 确保以这种方式导入
import { getToken } from '@/utils/auth';
import { uploadFile } from '@/api/serviceCenter';
const emit = defineEmits(['submit']);
// 定义上传请求参数的类型
interface UploadRequestOptions {
  file: File; // 文件类型
  onSuccess: (response: any) => void; // 上传成功回调函数
  onError: (error: any) => void; // 上传失败回调函数
  onProgress: (event: { percent: number }) => void; // 上传进度回调函数
}

// 上传参数
const upload = reactive({
  // 上传二维码弹窗变量
  open: false,
  // 弹出层标题
  title: '上传图片',
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Token: getToken() },
  // 上传的地址
  url: '/dev-api/api/index/imageUpload',
  imgurl: '',
  // 是否禁用上传
  disabled: true,
});
const formRef = ref<FormInstance>();
const uploadRef = ref<UploadInstance | null>(null);
// 表单数据
const form = reactive({
  remark: '',
  auditImage: '',
});

// 表单验证
const rules = reactive<FormRules>({
  remark: [
    {
      required: true,
      message: '请填写申请原因',
      trigger: 'change',
    },
  ],
});

// 表单提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      emit('submit', form);
    }
  });
};

// 删除/替换图片
const handleRemove = () => {
  form.auditImage = ''; // 清空图片 URL，允许用户上传新的图片
  uploadRef.value?.clearFiles(); // 清空文件列表，重置上传状态
};
// 自定义上传请求的逻辑
const customUploadRequest = async ({
  file,
  onSuccess,
  onError,
  onProgress,
}: UploadRequestOptions) => {
  // 文件大小限制为 5MB
  const maxFileSize = 5 * 1024 * 1024; // 5MB

  // 判断文件大小是否超过 5MB
  if (file.size > maxFileSize) {
    ElMessage({
      message: '文件大小不能超过 5MB',
      type: 'error',
    });
    return; // 阻止上传
  }

  // 调用封装的 uploadFile 函数来处理上传逻辑
  uploadFile(
    file,
    upload.url, // 上传的 URL
    upload.headers, // 自定义请求头
    (progressEvent: any) => {
      // 进度回调
      onProgress({ percent: Number(progressEvent.percent) }); // 进度回调
    },
    (response: any) => {
      onSuccess(response); // 上传成功的回调
      form.auditImage = response.data.url; // 假设返回的图片 URL 存储在 response.data.url
    },
    (error: any) => {
      onError(error); // 上传失败的回调
    }
  );
};
onMounted(async () => {});
</script>

<style lang="scss" scoped>
.replace-btn {
  position: absolute;
  bottom: 0;
  color: #fff;
  background: rgba(0, 0, 0, 0.6);
  width: 100%;
  left: 0;
  text-align: center;
  cursor: pointer;
}
.primary {
  width: 170px;
  color: #fff;
  background-color: #165dff;
  border-color: #165dff;
  height: 40px;
}
.primary:hover {
  opacity: 0.8;
}
</style>
